{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "61d4e4b4-80ae-49f9-b08a-354e8d92cc78",
   "metadata": {},
   "source": [
    "This notebook is intended to be downloaded and run locally, or run in cloud environments with persistent environments, like Sagemaker Studio Lab:\n",
    "\n",
    "[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/InsightSoftwareConsortium/itkwidgets/HEAD?labpath=examples%2FEnvironmentCheck.ipynb)\n",
    "[![Open In SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github.com/InsightSoftwareConsortium/itkwidgets/blob/main/examples/EnvironmentCheck.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58193a82-4e2d-4f04-8929-e2566b1b13c2",
   "metadata": {},
   "source": [
    "# Environment Check\n",
    "\n",
    "#### This notebook is designed to check the environment that you are running in to make sure that all example notebook dependencies and extensions are correctly installed. Simply select Run All Cells and let everything complete before running the example notebooks in this repository."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36eaad49-3b68-4806-8ba6-56eb0384d1da",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os, sys, re\n",
    "import importlib.util\n",
    "try:\n",
    "    import importlib.metadata as importlib_metadata\n",
    "except:\n",
    "    import importlib_metadata"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e09f10e-535d-4031-a092-96063969dc9c",
   "metadata": {},
   "source": [
    "#### Define the function to do the checking and install any missing dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b49c580-719a-4229-8785-4037162426d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "def _get_version(pkg):\n",
    "    try:\n",
    "        return importlib_metadata.version(pkg)\n",
    "    except:\n",
    "        pass\n",
    "    try:\n",
    "        return sys.modules[pkg].__version__\n",
    "    except:\n",
    "        return ''\n",
    "\n",
    "def _pkg_version_pre(values):\n",
    "    version, pre = None, False\n",
    "    if len(values) == 3:\n",
    "        version, pre = values[1:]\n",
    "    elif len(values) == 2:\n",
    "        pre = (values[1] == \"pre\")\n",
    "        version = values[1] if not pre else version\n",
    "    pkg = values[0]\n",
    "\n",
    "    return pkg, version, pre\n",
    "\n",
    "def check_for_package(req):\n",
    "    values = list(filter(None, re.split(r\"\\[.*\\]|==|>=|--| \", req))) # Grab the package name, version, and pre-release status\n",
    "    install_req = re.split(r\" --pre\", req)[0] # Grab the string we need for installation\n",
    "    pkg, version, pre = _pkg_version_pre(values)\n",
    "    if (importlib.util.find_spec(pkg.replace(\"-\", \"_\")) is None\n",
    "        or (version and _get_version(pkg) != version)):\n",
    "        print(f\"{install_req} not found, installing {pkg} now...\")\n",
    "        try:\n",
    "            if pre:\n",
    "                !{sys.executable} -m pip install --upgrade --pre -q \"{install_req}\"\n",
    "            else:\n",
    "                !{sys.executable} -m pip install --upgrade -q \"{install_req}\"\n",
    "        except Exception as e:\n",
    "            print(f'ERROR: {e}')\n",
    "    print(f\"{pkg} version {_get_version(pkg)} installed.\")\n",
    "    print(\"-----\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "871e8e65-5386-4c62-8ec3-bc4d80fada1a",
   "metadata": {},
   "source": [
    "#### List of notebook requirements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba6f3698-5af6-4b1f-b433-3804cde13494",
   "metadata": {},
   "outputs": [],
   "source": [
    "reqs = [\n",
    "    \"itkwidgets[all]>=1.0a24\",\n",
    "    \"imjoy-elfinder\",\n",
    "    \"imjoy-jupyter-extension\",\n",
    "    \"imjoy-jupyterlab-extension\",\n",
    "    \"itk\",\n",
    "    \"monai-weekly[nibabel, matplotlib, tqdm]\",\n",
    "    \"imageio\",\n",
    "    \"pyvista\",\n",
    "    \"dask[diagnostics]\",\n",
    "    \"toolz\",\n",
    "    \"scikit-image\",\n",
    "    \"pooch\",\n",
    "    \"matplotlib\",\n",
    "    \"tqdm\",\n",
    "    \"vtk\",\n",
    "    \"netCDF4\",\n",
    "    \"xarray\",\n",
    "    \"zarr\",\n",
    "    \"fsspec[http]\",\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63fb64d6-52bc-41a4-a7a6-6f9cf04ef0e1",
   "metadata": {},
   "source": [
    "#### Upgrade pip, just in case."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45d3f0e8-bf13-4c98-ac43-66901a9a704d",
   "metadata": {},
   "outputs": [],
   "source": [
    "!{sys.executable} -m pip install --upgrade -q pip"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff0514d1-53ca-4ff6-9fe4-142947a6aa86",
   "metadata": {},
   "source": [
    "#### Make sure that the package is installed and that it is the correct version."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "040c7e52-7e66-4063-838a-8eed90ac3be9",
   "metadata": {},
   "source": [
    "**WARNING**: Pip will sometimes raise errors for dependency conflicts. This errors can typically be safely ignored, but often times these issues can be avoided all together by creating a new, clean [python virtual environment](https://docs.python.org/3/library/venv.html) or [conda environment](https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html#managing-environments). You can follow the [Getting Started](https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html#) instructions if you are setting up conda for the fist time. If you continue to see errors or are unable to run the notebooks in this repo after running this notebook you can also [open an issue](https://github.com/InsightSoftwareConsortium/itkwidgets/issues/new)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e18e98c-575b-405e-bc49-1a7035882aa1",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "for req in reqs:\n",
    "    check_for_package(req)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44f4cd3b-b26f-4d0e-988b-9f9e1b9fac67",
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "if os.environ.get('CONDA_DEFAULT_ENV', None):\n",
    "    !conda install --yes -q --prefix {sys.prefix} -c conda-forge pyimagej\n",
    "else:\n",
    "    raise RuntimeError(\"No conda environment is activated, currently unable to install pyimagej. Please activate a conda environment and re-run this cell.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9218a450-0518-4ddb-8fe4-4b3d31bbb50c",
   "metadata": {},
   "source": [
    "#### Special case specific to running in AWS StudioLab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "556bdaee-a741-4e17-a274-b8f8e1122f44",
   "metadata": {},
   "outputs": [],
   "source": [
    "if \"studio-lab-user\" in os.getcwd():\n",
    "    # Make sure that the imjoy extension is installed in the Jupyter environment\n",
    "    # and not just the kernel environment since they may not be the same\n",
    "    !conda env update -n studiolab -f ../environment.yml\n",
    "    !conda install --yes -q --prefix {sys.prefix} -c conda-forge opencv nodejs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79cacab0-da6c-47f2-b007-d2a1c9305b7f",
   "metadata": {},
   "source": [
    "#### Make sure that the required extension(s) are loaded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00ad1eed-5fab-4076-8278-cdd393d2634f",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "let needReload = (typeof window.loadImJoyRPC === \"undefined\");\n",
    "if (needReload) {\n",
    "    needReload = false;\n",
    "    location.reload();\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5c99d93-c4b9-4e29-a1df-d116e18c869d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
